Determine if string contains a specific substring

Hello yet again.  I had this function working previously, but I made a few changes and now I can't remember what the original function was.  I wrote a function to give me the Object Number up to the last hyphen if the number contains any periods.  Otherwise, I just wanted to return the full string.  When I run the current script, though, the search function is incorrectly telling me there is a period even when there isn't one.  Here's my function which takes the Object Number as an input:

string getObjectNum(string s) {
    Buffer str = create;
    str = s;
    int len = length s;
    int j, i=0;
    Regexp dot = regexp(".");
    
    if (search(dot, str, 0)) {
        infoBox(str " contains a period");
        for (j=len-1; j>=0; j--) {
            if (s[j]=='-') {
                i = j;
                break;
            }
        }
        return s[0:i-1];
    } else {
        return s;
    }
}

So, currently, if I call this function with the string "1-4", it goes into the if section and displays the infoBox of (1-4 contains a period).  The reason I'm using search is that I thought it would be a bit faster than performing a loop through the string like the one below.  Plus I didn't want anyone to get confused if they look at my code later.  I'm almost positive that it has something to do with my Regexp variable, but I don't know what that is.

 

Chris


Christopher Cote - Mon Nov 07 12:30:08 EST 2016

Re: Determine if string contains a specific substring
Christopher Cote - Mon Nov 07 12:43:50 EST 2016

Never mind, I figured it out.  The problem was in fact with my Regexp variable.  Because I'm looking for the period character, I had to use the HTML ASCII value for it (.).  Otherwise, because regexp uses . as a wildcard instead of the actual character.

 

Chris

Re: Determine if string contains a specific substring
Mathias Mamsch - Mon Nov 07 15:30:01 EST 2016

One note: Declare the buffer as a global variable, or do not forget to delete it. Otherwise you will suffer from massive slowdown (see other threads on topic memory management). Regards, Mathias

Re: Determine if string contains a specific substring
Mike.Scharnow - Tue Nov 08 03:51:57 EST 2016

Christopher Cote - Mon Nov 07 12:43:50 EST 2016

Never mind, I figured it out.  The problem was in fact with my Regexp variable.  Because I'm looking for the period character, I had to use the HTML ASCII value for it (.).  Otherwise, because regexp uses . as a wildcard instead of the actual character.

 

Chris

Hint: that's why "escape characters" exist (https://en.wikikipedia.org/wiki/Escape_character). In your case, you could have searched for \., where \ is the escape character.